package com.rabbiter.em.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbiter.em.common.Result;
import com.rabbiter.em.config.AliPayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PayService {


    @Resource
    private AliPayProperties aliPayProperties;
    @Resource
    private OrderService orderService;
    @Resource
    private AlipayClient alipayClient;

    public Result generatePayPage(String orderNo, Long userId) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayProperties.getNotifyUrl());
        request.setReturnUrl(aliPayProperties.getReturnUrl());
        ObjectMapper objectMapper = new ObjectMapper();
        //远程调用
        //需要查询订单信息  根据订单号 用户id查询
        Map<String, Object> orderInfo = orderService.selectByOrderNo(orderNo);
        if (orderInfo == null || orderInfo.size() <= 0) {
            return Result.error("400", "订单信息不存在！");
        }
        if (!"待付款".equals(MapUtil.getStr(orderInfo, "state"))) {
            return Result.error("400", "订单状态错误");
        }
        if (MapUtil.getLong(orderInfo, "userId") != userId) {
            return Result.error("400", "订单信息不存在！");
        }
        Map<String, Object> bizContent = new HashMap<>();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", MapUtil.getDouble(orderInfo, "price"));
        bizContent.put("subject", MapUtil.getStr(orderInfo, "standard", "默认商品"));
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("time_expire", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.offsetMinute(new Date(), 30)));
        Map<String, Object> goodsDetails = new HashMap<>();
        goodsDetails.put("good_id", MapUtil.getLong(orderInfo, "goodId"));
        goodsDetails.put("good_name", MapUtil.getStr(orderInfo, "goodName"));
        goodsDetails.put("order_id", MapUtil.getLong(orderInfo, "orderId"));
        goodsDetails.put("account_id", userId);
//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);
        try {
            bizContent.put("body", objectMapper.writeValueAsString(goodsDetails));
            request.setBizContent(objectMapper.writeValueAsString(bizContent));
            AlipayTradePagePayResponse response = null;
            response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                return Result.success(response.getBody());
            } else {
                return Result.error("400", "失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("400", "失败");
    }

    public Result query(String outTradeNo, String tradeNo) {
        //设置请求参数
        try {
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","+"\"trade_no\":\""+ tradeNo +"\"}");
            String result = alipayClient.execute(alipayRequest).getBody();
            Map map = JSONUtil.toBean(result, Map.class);
            Map response = (Map)map.get("alipay_trade_query_response");
            String tradeStatus = MapUtil.getStr(response, "trade_status");
            if (tradeStatus != null && ("TRADE_SUCCESS".equals(tradeStatus)
                    || "TRADE_FINISHED".equals(tradeStatus))) {
                Map<String, Object> orderInfo = orderService.selectByOrderNo(outTradeNo);
                if ("待付款".equals(MapUtil.getStr(orderInfo, "state"))) {
                    orderService.payOrder(outTradeNo);
                }
                return Result.success();
            } else if (tradeStatus != null && "TRADE_CLOSED".equals(tradeStatus)) {
                return Result.error("401", "支付超时");
            } else if (tradeStatus != null && "WAIT_BUYER_PAY".equals(tradeStatus)) {
                return Result.error("402", "等待买家付款");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.error("400", "no_query_pay");
    }
}
/*
交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、
        TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、
        TRADE_SUCCESS（交易支付成功）、
        TRADE_FINISHED（交易结束，不可退款）*/
